<template>
  <el-dialog
    :visible.sync="isVisible"
    title="添加路径巡航点"
    width="600px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @closed="onClose"
  >
    <div class="dialog-container">
      <el-form
        ref="pathForm"
        :model="path"
        :rules="pathRules"
        label-width="100px"
      >
        <el-form-item label="名称:" prop="name">
          <el-input v-model="path.name" placeholder="请输入名称" />
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer">
      <el-button @click="onCancel">取消</el-button>
      <el-button type="primary" @click="onSave">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addPath } from '@/api/camera'; // 确保导入正确的接口

export default {
  name: 'AddPathDialog',
  data() {
    return {
      isVisible: false,
      path: {
        name: '',
      },
      pathRules: {
        name: [
          {
            required: true,
            message: '请输入名称',
            trigger: ['blur', 'change'],
          },
        ],
      },
    };
  },
  computed: {
    // 当前播放的视频对象
    currentVideo() {
      return this.$store.getters['playVideo/getCurrentPlayingVideo'];
    },
    // config配置
    config() {
      return this.$store.getters['websocketClient/config'];
    },
  },
  methods: {
    /**
     * 显示添加对话框
     */
    show() {
      this.isVisible = true;
      this.path = {
        name: '',
      };
    },
    /**
     * 隐藏对话框
     */
    onClose() {
      this.isVisible = false;
      // 清除表单校验
      this.$refs.pathForm.resetFields();
    },
    /**
     * 取消
     */
    onCancel() {
      this.isVisible = false;
      // 清除表单校验
      this.$refs.pathForm.resetFields();
    },
    /**
     * 保存
     */
    onSave() {
      this.$refs.pathForm.validate(async (valid) => {
        if (!valid) {
          return false;
        } else {
          const param = {
            camera_id: this.currentVideo.cameraId,
            path_name: this.path.name,
          };
          const res = await addPath(param);
          if (res.code === 200) {
            this.$message.success('添加成功');
            this.isVisible = false;
            this.$emit('refresh-table');
            // 添加成功并发送指令
            this.$store.dispatch('websocketClient/sendMessage', {
              ws_url: `${process.env.VUE_APP_WEBSOCKET_URL}/${this.currentVideo.cameraId}`,
              message: {
                cameraId: this.currentVideo.cameraId,
                command: this.config['btnCommand']['pathSet'],
                data: {
                  name: this.path.name,
                },
              },
            });
          } else {
            this.$message.error('添加失败');
          }
          this.isVisible = false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.dialog-container {
  padding: 20px;
}
</style>
